const baseUrl = 'https://jy.cqcvc.edu.cn:8090/api';
const http = {
	baseUrl,
	request(config) {
		config = beforeRequest(config);

		if (!config) {
			return Promise.reject({
				data: 'token过期，请登录'
			})
		}

		config.url = this.baseUrl + config.url;
		return new Promise((resolve, reject) => {
			uni.request(config)
				.then(res => {
					const response = beforeResponse(res);
					resolve(response);
				})
				.catch(err => {
					errorHandle(err);
					reject(err);
				});
		});
	},
	get(url, data, noToken) {
		return this.request({
			url,
			data,
			method: "GET",
			proxy: true,
			noToken,
		});
	},
	put(url, data, noToken) {
		return this.request({
			url,
			data,
			method: "PUT",
			proxy: true,
			noToken,
		});
	},
	post(url, data, noToken) {
		return this.request({
			url,
			data,
			method: "POST",
			proxy: true,
			noToken,
		});
	},
	delete(url, data, noToken) {
		return this.request({
			url,
			data,
			method: "DELETE",
			proxy: true,
			noToken,
		});
	}
};

const beforeRequest = (config) => {
	console.log("请求拦截器", config)
	config.header = {
		"Accept": "application/json", // 接受的数据类型
		"Content-Type": "application/json",
	}
	if (!config.noToken) {
		if (uni.getStorageSync('token')) {
			config.header['Authorization'] = "Token " + uni.getStorageSync('token')
		} else {
			uni.reLaunch({
				url: '/pages/login/login'
			});
			return null;
		}
	}

	return config;
};

const beforeResponse = (response) => { // 这里的参数名应该是 response 而不是 config

	if (response.statusCode < 300) {
		console.log("响应拦截器", response);

		return response;
	} else if (response.statusCode == 401 ||
		response.statusCode == 403) {
		uni.showToast({
			title: "没有权限,请先登录",
			icon: 'none'
		})
		uni.reLaunch({
			url: '/pages/login/login'
		})
		console.log(response.data)
	} else {
		return Promise.reject(response)
	}
};

const errorHandle = (err) => { // 这里添加 err 参数
	console.log("网络异常，请求失败", err); // 字符串需要使用引号括起来，即 "网络异常，请求失败"
};

export default http;